<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input v-model="listQuery.name" placeholder="日子就" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter" />
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                查询
            </el-button>
            <!-- <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                @click="handleCreate">
                添加
            </el-button> -->
        </div>
        <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;"
            @sort-change="sortChange">
            <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80"
                :class-name="getSortClass('id')">
                <template slot-scope="{row}">
                    <span>{{ row.id }}</span>
                </template>
            </el-table-column>
            <el-table-column label="任务类型" width="150px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.name }}</span>
                </template>
            </el-table-column>
            <el-table-column label="总数" width="150px" align="center">
                <template slot-scope="{row}">
                    <el-image v-if="row.lxtypes == 1 || row.lxtypes == 3"  style="width: 100px; height: 100px"  :src="row.urls" :fit="fit"></el-image>
                    <span v-if="row.lxtypes == 2">{{ row.urls }}</span>

                </template>
            </el-table-column>
            <el-table-column label="资源类型" width="150px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.lxtypes == 1 ? '图片' : row.lxtypes ==2 ? '视频':row.lxtypes == 3 ? '头像':'异常' }}</span>
                </template>
            </el-table-column>

            <el-table-column label="创建时间" width="300px" align="center">
                <template slot-scope="{row}">
                    <el-tag>{{ row.times | parseTime('{y}-{m}-{d} {h}:{i}') }} </el-tag>
                </template>
            </el-table-column>

            <el-table-column label="状态" class-name="status-col" width="100">
                <template slot-scope="{row}">
                    <el-tag :type="row.status | statusFilter">
                        {{ row.status == 1 ? '正常' : row.status == 2 ? '暂停' : '异常' }}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
                <template slot-scope="{row,$index}">
                    <!-- <el-button type="primary" size="mini" @click="handleUpdate(row)">
                        编辑
                    </el-button> -->
                    <el-button size="mini" type="danger" @click="handleDelete(row, $index)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
            @pagination="getList" />

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px"
                style="width: 400px; margin-left:50px;">
                <el-form-item label="资源名称" prop="username">
                    <el-input v-model="temp.name" />
                </el-form-item>
                <el-form-item label="资源类型">
                    <el-radio-group v-model="temp.lxtypes">
                        <el-radio :label="1">图片</el-radio>
                        <el-radio :label="2">视频</el-radio>
                        <el-radio :label="3">头像</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="图片" v-if="temp.lxtypes == 1 || temp.lxtypes == 3">
                    <el-upload :action="getimageurl" list-type="picture-card" :on-success="imguploadSuccess"
                        :auto-upload="true" :multiple="false">
                        <i slot="default" class="el-icon-plus"></i>
                        <div slot="file" slot-scope="{file}">
                            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                            <span class="el-upload-list__item-actions">
                                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                    <i class="el-icon-zoom-in"></i>
                                </span>
                                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                                    <i class="el-icon-download"></i>
                                </span>
                                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                                    <i class="el-icon-delete"></i>
                                </span>
                            </span>
                        </div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="视频" v-if="temp.lxtypes == 2">
                    <el-upload ref="uploadFile" drag :action="getvideourl" :auto-upload="true" :multiple="false" :limit="1"
                        accept=".mp4" :before-upload="beforeUpload" :on-success="uploadSuccess" :on-error="uploadError"
                        :on-exceed="uploadExceed">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">只能上传mp4，且不超过10M，一次只能上传一个</div>
                    </el-upload>
                </el-form-item>


                <el-form-item label="状态">
                    <el-select v-model="temp.status" class="filter-item" placeholder="Please select">
                        <el-option v-for="item in statusOptions" :key="item.key" :label="item.display_name"
                            :value="item.key" />
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                    取消
                </el-button>
                <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
                    修改
                </el-button>
            </div>
        </el-dialog>

        <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
            <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
                <el-table-column prop="key" label="Channel" />
                <el-table-column prop="pv" label="Pv" />
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { fetchList, fetchPv, createArticle, updateArticle, getDel } from '@/api/rz'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
const statusOptions = [
    { key: 1, display_name: '正常' },
    { key: 2, display_name: '暂停' }
]
export default {
    name: 'ComplexTable',
    components: { Pagination },
    directives: { waves },
    filters: {
        statusFilter(status) {
            const statusMap = {
                1: 'success',
                2: 'info',
                3: 'danger'
            }
            return statusMap[status]
        },
        typeFilter(type) {
            return calendarTypeKeyValue[type]
        }
    },
    data() {
        return {
            tableKey: 0,
            list: null,
            total: 0,
            listLoading: true,
            listQuery: {
                page: 1,
                limit: 20,
                types: '',
                name: '',
            },
            statusOptions,
            imagecropperShow: false,
            imagecropperKey: 0,
            image: 'https://wpimg.wallstcn.com/577965b9-bb9e-4e02-9f0c-095b41417191',
            showReviewer: false,
            temp: {
                id: undefined,
                name: '',
                lxtypes: 1,
                urls: '',
                content: '',
                baseinfo: '',
                status: 1
            },
            dialogFormVisible: false,
            dialogStatus: '',
            textMap: {
                update: 'Edit',
                create: 'Create'
            },
            dialogPvVisible: false,
            pvData: [],
            rules: {
                type: [{ required: true, message: 'type is required', trigger: 'change' }],
                title: [{ required: true, message: 'title is required', trigger: 'blur' }]
            },
            downloadLoading: false,
            dialogImageUrl: '',
            dialogVisible: false,
            disabled: false,
            getimageurl: 'http://121.62.23.47:8190/admindl/Ziy/addimage',
            getvideourl: 'http://121.62.23.47:8190/admindl/Ziy/addvideo',
        }
    },
    created() {
        this.getList()
    },
    methods: {
        getList() {
            this.listLoading = true
            fetchList(this.listQuery).then(response => {
                console.log(response.data)
                this.list = response.data.list
                this.total = response.data.count
                setTimeout(() => {
                    this.listLoading = false
                }, 1.5 * 1000)
            })
        },
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        handleModifyStatus(row, status) {
            this.$message({
                message: '操作Success',
                type: 'success'
            })
            row.status = status
        },
        sortChange(data) {
            const { prop, order } = data
            if (prop === 'id') {
                this.sortByID(order)
            }
        },
        sortByID(order) {
            if (order === 'ascending') {
                this.listQuery.sort = '+id'
            } else {
                this.listQuery.sort = '-id'
            }
            this.handleFilter()
        },
        resetTemp() {
            this.temp = {
                id: undefined,
                name: '',
                status: 1,
                lxtypes: 1
            }
        },
        handleCreate() {
            this.resetTemp()
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        createData() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    createArticle(this.temp).then(() => {
                        this.dialogFormVisible = false
                        this.$notify({
                            title: 'Success',
                            message: 'Created Successfully',
                            type: 'success',
                            duration: 2000
                        })
                        this.getList();
                    })
                }
            })
        },
        handleUpdate(row) {
            this.temp = Object.assign({}, row) // copy obj
            this.dialogStatus = 'update'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        updateData() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    const tempData = Object.assign({}, this.temp)
                    updateArticle(tempData).then(() => {
                        const index = this.list.findIndex(v => v.id === this.temp.id)
                        this.list.splice(index, 1, this.temp)
                        this.dialogFormVisible = false
                        this.$notify({
                            title: 'Success',
                            message: 'Update Successfully',
                            type: 'success',
                            duration: 2000
                        })
                    })
                }
            })
        },
        handleDelete(row, index) {
            let temp = {
                id: row.id
            }
            getDel(temp).then(() => {
                this.$notify({
                    title: 'Success',
                    message: 'Created Successfully',
                    type: 'success',
                    duration: 2000
                })
            })
            this.list.splice(index, 1)
        },


        formatJson(filterVal) {
            return this.list.map(v => filterVal.map(j => {
                if (j === 'timestamp') {
                    return parseTime(v[j])
                } else {
                    return v[j]
                }
            }))
        },
        getSortClass: function (key) {
            const sort = this.listQuery.sort
            return sort === `+${key}` ? 'ascending' : 'descending'
        },
        beforeUpload(file) {
            const { name, size } = file;
            const index = name.lastIndexOf('.');
            // 判断文件名是否有后缀，没后缀文件错误
            if (index === -1) {
                this.$notify.error({
                    title: '错误',
                    message: '文件错误，请重新上传！',
                });
                return false;
            }
            const fileType = name.substr(index + 1);
            const acceptFileTypes = ['mp4'];
            // 判断文件类型
            if (!acceptFileTypes.includes(fileType)) {
                this.$notify.error({
                    title: '错误',
                    message: '文件类型错误，请重新上传！',
                });
                return false;
            }
            // 判断文件大小
            if (size > 10 * 1024 * 1024) {
                this.$notify.error({
                    title: '错误',
                    message: '文件大小超过10M，请重新上传！',
                });
                return false;
            }
            // 默认true
            return true;
        },

        // 上传接口调取成功status为200
        uploadSuccess(res) {
            if (res.code === 200) {  // 文件上传成功
                console.log(res)
                this.temp.urls = res.data.url
                this.temp.content = res.data.base64
                this.$notify.success({
                    title: '成功',
                    message: '文件上传成功！',
                });
            } else {
                this.uploadError();
            }
        },

        // 文件上传失败
        uploadError() {
            this.$notify.error({
                title: '错误',
                message: '文件上传失败！',
            });
        },

        // 文件个数超过限制
        uploadExceed() {
            this.$notify.warning({
                title: '提示',
                message: '您已添加了一个文件，如需替换，请先删除已添加的文件！',
            });
        },
        handleRemove(file) {
            console.log(file);
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handleDownload(file) {
            console.log(file);
        },
        // 图片上传
        imguploadSuccess(res) {
            if (res.code === 200) {  // 文件上传成功
                console.log(res)
                this.temp.urls = res.data.url
                this.temp.content = res.data.base64
                this.$notify.success({
                    title: '成功',
                    message: '文件上传成功！',
                });
            } else {
                this.uploadError();
            }
        },
    }
}
</script>
